package br.ufms.odontologico.bo;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.ufms.odontologico.model.Agendamento;
import br.ufms.odontologico.model.Cliente;
import br.ufms.odontologico.util.JpaUtils;

@ViewScoped
@ManagedBean
public class ClienteBO extends GenericBO<Cliente> {

	@SuppressWarnings("unchecked")
	public List<Cliente> listByNome(String nome) {
		Object obj = null;
		EntityTransaction t = getEm().getTransaction();
		t.begin();
		try{
			Query qr = getEm().createQuery("from Cliente where nome like ?");
			qr.setParameter(1, JpaUtils.likeAny(nome));
			obj = qr.getResultList();
			t.commit();
		}catch (Exception e) {
			t.rollback();
			e.printStackTrace();
		}
		return (obj!=null && obj instanceof List<?>) ?((List<Cliente>) obj) :null;
	}

	public Cliente novoCliente(Cliente cli) {
		EntityTransaction t = getEm().getTransaction();
		t.begin();
		try{
			if(!this.insert(cli)){
				cli=null;
			}
			t.commit();
		}catch (Exception e) {
			t.rollback();
		}
		return cli;
	}

	@SuppressWarnings("unchecked")
	public List<Agendamento> getAgendamentos(Cliente cliente) {
		Object obj = null;
		EntityTransaction t = getEm().getTransaction();
		t.begin();
		try{
			Query qr = getEm().createQuery("from Agendamento where cliente = ?");
			qr.setParameter(1, cliente);
			obj = qr.getResultList();
			t.commit();
		}catch (Exception e) {
			t.rollback();
			e.printStackTrace();
		}
		return (obj!=null && obj instanceof List<?>) ?((List<Agendamento>) obj) :null;
	}

}
